package com.huluobo.a2209mdmdemo.views

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_http.Const
import com.hyphenate.EMCallBack
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMMessageBody
import com.hyphenate.chat.EMTextMessageBody
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/3/10.
 */

data class ChatBean(val contact: String, val chatType: ChatType)

@Composable
fun ChatPage(navHostController: NavHostController, json: String) {

    val chatBean = Gson().fromJson(json, ChatBean::class.java)

    //聊天记录的数据源,发送消息或者接收消息都是往当前数据源中添加数据并展示
    var messages by remember {
        mutableStateOf<List<EMMessage>>(emptyList())
    }

    //LazyColumn的状态
    val listState = rememberLazyListState()

    //协程的作用域,用于更新滚动
    val coroutineScope = rememberCoroutineScope()

    //一条消息的内容
    var message by remember {
        mutableStateOf("")
    }

    //接收消息的监听器
    val messageListener = EMMessageListener {
        //当消息产生变化的时候
        it?.let {
            //添加接收到的消息到数据源中
            messages = messages + it
            //滚动到最下方
            coroutineScope.launch {
                listState.scrollToItem(messages.size - 1)
            }
        }
    }

    //开启协程来注册消息监听器
    DisposableEffect(Unit) {
        //注册消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        onDispose {
            //移除消息监听器
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    Scaffold(bottomBar = {
        //聊天输入框
        OutlinedTextField(modifier = Modifier
            .fillMaxWidth()
            .padding(5.dp), value = message, onValueChange = { message = it }, trailingIcon = {
            Icon(imageVector = Icons.Default.Send, contentDescription = "", modifier = Modifier.clickable {
                //发送消息
                val emMessage = EMMessage.createTextSendMessage(message, chatBean.contact)
                emMessage.chatType = ChatType.Chat
                emMessage.setMessageStatusCallback(object : EMCallBack {
                    override fun onSuccess() {
                        val emMessage = EMMessage.createTextSendMessage(message, EMClient.getInstance().currentUser)
                        messages = messages + emMessage
                        message = ""
                        //发送消息同样滚动到最下方
                        coroutineScope.launch {
                            listState.scrollToItem(messages.size - 1)
                        }
                    }

                    override fun onError(code: Int, error: String?) {
                        ToastUtils.showLong("发送消息失败")
                    }
                })
                EMClient.getInstance().chatManager().sendMessage(emMessage)
            })
        })
    }) {
        Column(
            Modifier
                .padding(it)
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            BaseTitle(title = "与${chatBean.contact}聊天", navHostController = navHostController)
            Spacer(modifier = Modifier.height(20.dp))
            Divider()
            Spacer(modifier = Modifier.height(20.dp))
            //存放聊天记录
            LazyColumn(state = listState, verticalArrangement = Arrangement.spacedBy(10.dp), content = {
                items(messages) { message ->
                    ChatItem(message = message)
                }
            })

        }
    }
}

@Composable
fun ChatItem(message: EMMessage) {
    Row(
        //根据消息的发送方向来改变消息的布局,如果是发送消息就是右侧的布局,如果是接收消息就是左侧布局
        horizontalArrangement = if (message.direct() == EMMessage.Direct.SEND) Arrangement.End else Arrangement.Start,
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .padding(20.dp)
            .fillMaxWidth()
    ) {
        if (message.direct() == EMMessage.Direct.SEND) {
            Text(text = (message.body as EMTextMessageBody).message)
            Spacer(modifier = Modifier.width(20.dp))
            AsyncImage(
                model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                contentDescription = "",
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape),
                contentScale = ContentScale.Crop
            )
        } else {
            AsyncImage(
                model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                contentDescription = "",
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape),
                contentScale = ContentScale.Crop
            )
            Spacer(modifier = Modifier.width(20.dp))
            Text(text = (message.body as EMTextMessageBody).message)
        }

    }
}